﻿using AutoMapper;
using Common.Infrastructrue.Interface;
using Common.Infrastructrue.Reponsistory;
using Common.Service;
using MediatR;
using Microsoft.Data.SqlClient.Server;
using RabitPart.ReadApi.Application.RBACrelationship.RELUserShow;
using Tea.Utils;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory;

namespace RabitPart.ReadApi.Application.TraceabilityFile
{
    public class TraceabilityShowCommonHandler : IRequestHandler<TraceabilityShowComman, ApiResult<APIPagingresult<IList<TraceabilityShowCommanResponstity>>>>
    {
        private readonly IMapper mapper;
        private readonly ICompanymanageResponstity companyRE;
        private readonly ILogger<TraceabilityShowCommonHandler> logger;

        public TraceabilityShowCommonHandler(IMapper mapper, ICompanymanageResponstity companyRE, ILogger<TraceabilityShowCommonHandler> logger)
        {
            this.mapper = mapper;
            this.companyRE = companyRE;
            this.logger = logger;
        }

        public async Task<ApiResult<APIPagingresult<IList<TraceabilityShowCommanResponstity>>>> Handle(TraceabilityShowComman request, CancellationToken cancellationToken)
        {
            // 获取所有公司管理数据
            var companyList = await companyRE.GetAllAsync(x=>x.IsDelete==true);

            // 使用 mapper 将 Companymanage 转换为 TraceabilityShowCommanResponstity
            var mappedList = mapper.Map<List<TraceabilityShowCommanResponstity>>(companyList);

            // 进行分页
            var pagedResult = mappedList
                .OrderBy(x => x.ProductId) // 确保 TraceabilityShowCommanResponstity 有 CmId 属性
                .Skip((request.pageindex - 1) * request.pagesize)
                .Take(request.pagesize)
                .ToList();

            // 创建分页结果
            var pagingResult = new APIPagingresult<IList<TraceabilityShowCommanResponstity>>()
            {
                TotalCount = mappedList.Count,
                TotalPage = (int)Math.Ceiling(mappedList.Count * 1.0 / request.pagesize),
                Data = pagedResult
            };

            return ApiResult<APIPagingresult<IList<TraceabilityShowCommanResponstity>>>.Success(pagingResult,StatusCodeEnum.Ok);
        }


    }
}
